import { StoreHelper } from "./storeHelper";

class CreepHelper{
  /**
  * creep 拾取方法（解决creep工作的时候不拾取，拾取时候不工作）
  */
  public static creepPickup(creep:Creep,blackIdList?:Array<string>): void {
    if(!creep.memory.stopWorkTick){
      creep.memory.stopWorkTick = 0;
    }
    creep.memory.working = false;
    creep.memory.stopWorkTick += 1;
    // 寻找资源目标
    let source: any = null;

    if(!creep.memory.source){
      let sourceStorage = StoreHelper.findClosestNotEmptyStorage(creep,blackIdList);
      let sourceContainer:any = StoreHelper.findClosestNotEmptyContainer(creep,blackIdList);
      let sourceDropped:any = StoreHelper.findClosestDroppedResources(creep);
      // 寻找最靠近的能量资源
      let sourceList:any[] = [sourceStorage,sourceContainer,sourceDropped];
      sourceList = sourceList
        .filter((resource)=>{ return resource != null &&  resource != undefined })
        .sort((resourceA:any,resourceB:any)=>{ 
            return creep.pos.getRangeTo(resourceA) - creep.pos.getRangeTo(resourceB)
          });
      if(sourceList.length > 0){
        source = sourceList[0];
        creep.memory.source = { id:source.id,pos:source.pos };
      }
    }
    else {
      source = Game.getObjectById(creep.memory.source?.id);
      if(source === null){
        creep.memory.source = undefined;
        return;
      }
    }
    
    // 执行取资源和移动逻辑
    if (source) {
      if(source.structureType === STRUCTURE_CONTAINER || source.structureType === STRUCTURE_STORAGE){
        // 资源获取
        let result = creep.withdraw(source, RESOURCE_ENERGY);
        if(result === ERR_NOT_IN_RANGE) {
          creep.go(source.pos);
        }
        if(result != OK && result != ERR_NOT_IN_RANGE){
          creep.memory.source = undefined;
        }
      }
      else{
        // 拾取
        let result = creep.pickup(source);
        if (result === ERR_NOT_IN_RANGE) {
          creep.go(source);
        }
        if(result != OK && result != ERR_NOT_IN_RANGE){
          creep.memory.source = undefined;
        }
      }
    }
    else {
      // 如果旁边都没资源，进行采集
      let target = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
      if(target){
        const result = creep.harvest(target);
        if (result === ERR_NOT_IN_RANGE) {
          creep.go(target);
        }
      }
    }

    //如果已经携带满了把creep更改为工作状态
    if(creep.store.getFreeCapacity(RESOURCE_ENERGY) === 0 && creep.memory.working === false){
      creep.memory.stopWorkTick = 0;
      creep.memory.working = true;
    }
  }

  // 找到离指定位置最近的未满存储设施
  public static findNotFullExtension(creep:Creep): StructureExtension | null {

    const extensions = creep.pos.findClosestByPath(FIND_MY_STRUCTURES,{
      filter: function(structure){
        return structure.structureType === STRUCTURE_EXTENSION && structure.store.getFreeCapacity(RESOURCE_ENERGY) > 0
      }
    }) as StructureExtension;

    return extensions;
  }
}

export { CreepHelper };